<template>
  <div class="files-preview">
    <div v-if="previewList && previewList.length > 0">
      <div v-if="blockDisplayArr.length" class="list-view">
        <preview-block-item
          v-for="(fileItem, idx) in blockDisplayArr"
          :key="fileItem.id"
          :file-item="fileItem"
          :show-download="showDownload"
          :show-delete="showDelete"
          @preview="onPreview(fileItem)"
          @download="onDownload(fileItem)"
          @delete="onDelete(idx)"></preview-block-item>
      </div>
      <div v-if="listDisplayArr.length" class="list-view">
        <preview-list-item
          v-for="(fileItem, idx) in listDisplayArr"
          :key="fileItem.id"
          :file-item="fileItem"
          :small-layout="smallLayout"
          :show-download="showDownload"
          :show-delete="showDelete"
          @preview="onPreview(fileItem)"
          @download="onDownload(fileItem)"
          @delete="onDelete(idx)"></preview-list-item>
      </div>
    </div>
    <p class="empty" v-else></p>
    <video-preview-dialog :visible.sync="videoPreviewVisible" :player-options="playerOptions"></video-preview-dialog>
  </div>
</template>

<script>
import { guid } from '@utility/utility'
import { FILE_PREVIEW_TYPE } from '@utility/dict'
// eslint-disable-next-line no-unused-vars
import { getFilePreviewUrl, downloadFile } from '@api/api.js'
import VideoPreviewDialog from './VideoPreviewDialog.vue'
import PreviewBlockItem from './PreviewBlockItem'
import PreviewListItem from './PreviewListItem.vue'

export default {
  name: 'UploadPreview',
  components: {
    VideoPreviewDialog,
    PreviewBlockItem,
    PreviewListItem,
  },
  props: {
    fileList: {
      type: Array,
      default() {
        return []
      },
    },
    layout: {
      type: String,
      default: 'auto', // list, block, auto, mixed (auto：只有图片和视频时，为block模式；图文混排时为list模式；mixed: 图片、视频排在前面，展示为block，文档展示为list)
    },
    showDownload: {
      type: Boolean,
      default: true,
    },
    showDelete: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      IMG_TYPES: ['jpeg', 'png', 'jpg'],
      VIDEO_TYPES: ['mp4', 'rmp4'],
      DOC_TYPES: ['xlsx', 'xls', 'doc', 'docx', 'pdf', 'txt', 'ppt', 'pptx', 'ofd', 'wps'],
      videoPreviewVisible: false,
      playerOptions: {
        language: 'zh-CN',
        aspectRatio: '16:9',
        fluid: true,
        sources: [
          {
            type: 'video/mp4',
            src: '',
          },
        ],
        poster: '',
        autoplay: false,
        controls: true,
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true, // 是否显示全屏按钮
        },
      },
      smallLayout: false,
    }
  },
  computed: {
    showType() {
      if (this.previewList && this.previewList.length) {
        if (this.layout === 'auto') {
          const docItem = this.previewList.find(item => {
            return FILE_PREVIEW_TYPE.doc === item.previewType
          })
          if (docItem) {
            return 'list'
          } else {
            return 'block'
          }
        }
      }
      return this.layout
    },
    previewList() {
      if (this.fileList && this.fileList.length) {
        return this.fileList.map(item => {
          if (!item.id) {
            item.id = guid()
          }
          item.fileType = item.fileType.toLowerCase()
          let previewType = ''
          if (this.IMG_TYPES.includes(item.fileType)) {
            previewType = FILE_PREVIEW_TYPE.img
          } else if (this.VIDEO_TYPES.includes(item.fileType)) {
            previewType = FILE_PREVIEW_TYPE.video
          } else if (this.DOC_TYPES.includes(item.fileType)) {
            previewType = FILE_PREVIEW_TYPE.doc
          }
          const previewPath = getFilePreviewUrl(
            (previewType === FILE_PREVIEW_TYPE.doc && item.thumbnailPath) || item.sourcePath
          )
          return { ...item, previewType, previewPath }
        })
      }
      return []
    },
    previewImgs() {
      if (this.previewList) {
        return this.previewList.filter(item => item.previewType === FILE_PREVIEW_TYPE.img).map(item => item.sourcePath)
      }
      return []
    },
    listDisplayArr() {
      if (this.layout === 'mixed') {
        return this.previewList.filter(item => item.previewType === FILE_PREVIEW_TYPE.doc)
      } else if (this.showType === 'list') {
        return this.previewList
      } else {
        return []
      }
    },
    blockDisplayArr() {
      if (this.layout === 'mixed') {
        return this.previewList.filter(item => item.previewType !== FILE_PREVIEW_TYPE.doc)
      } else if (this.showType === 'block') {
        return this.previewList
      } else {
        return []
      }
    },
  },
  created() {
    window.addEventListener('resize', this.resetSmallLayout)
  },
  mounted() {
    this.resetSmallLayout()
  },
  watch: {},
  filters: {},
  methods: {
    resetSmallLayout() {
      const rootWidth = this.$el.clientWidth
      if (rootWidth < 240) {
        this.smallLayout = true
      } else {
        this.smallLayout = false
      }
    },
    inited(viewer) {
      this.$viewer = viewer
    },
    onPreview(item) {
      if (item.previewType === FILE_PREVIEW_TYPE.img) {
        this.previewImg(item)
      } else if (item.previewType === FILE_PREVIEW_TYPE.video) {
        this.previewVedio(item)
      } else if (item.previewType === FILE_PREVIEW_TYPE.doc) {
        this.previewDoc(item)
      }
    },
    previewImg(fileItem) {
      const previewIdx = this.previewImgs.findIndex(item => item === fileItem.previewPath)
      this.$viewerApi({
        images: this.previewImgs,
        options: {
          initialViewIndex: previewIdx,
          title: false,
          // title: [1, (image, imageData) => `${image.alt} (${imageData.naturalWidth} × ${imageData.naturalHeight})`],
        },
      })
    },
    previewVedio(fileItem) {
      this.playerOptions.sources[0].src = fileItem.previewPath
      this.playerOptions.poster = fileItem.thumbnailPath
      this.videoPreviewVisible = true
    },
    // 查看 document
    previewDoc(fileItem) {
      const routeData = this.$router.resolve({
        name: 'PDF_PAGE',
        query: {
          url: fileItem.previewPath,
        },
      })
      window.open(routeData.href, '_blank')
    },
    // 下载
    onDownload(fileItem) {
      // console.log('fileItem..', fileItem)
      const req = `?fileName=${encodeURIComponent(fileItem.name)}&filePath=${fileItem.sourcePath}`
      const link = document.createElement('a')
      link.target = 'targetName'
      link.href = downloadFile(req)
      console.log('link.href :>> ', link.href)
      link.click()
    },

    onDelete(i) {
      this.$confirm('确定要删除附件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // eslint-disable-next-line
          this.fileList.splice(i, 1)
          this.$emit('fileRemove')
        })
        .catch(() => {})
    },
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resetSmallLayout)
  },
}
</script>

<style lang="scss" scoped>
.files-preview {
  width: 100%;
  .empty {
    font-size: 14px;
  }

  .list-view {
    display: flex;
    align-items: center;
    font-size: 14px;
    flex-wrap: wrap;
  }
}
</style>
